from werkzeug.security import generate_password_hash, check_password_hash
from app.utils.mysql_util import MySQLUtil
from datetime import datetime
from app.models.user import User

class AuthService:
    def __init__(self):
        self.db_util = MySQLUtil()

    def get_user_by_id(self, user_id):
        try:
            sql = '''
                SELECT id, username, nickname, email, phone, avatar, status, 
                       password, is_deleted, created_time, update_time, last_login_time
                FROM user
                WHERE id = %s AND is_deleted = 0
            '''
            user_data = self.db_util.get_one(sql, (user_id,))
            if user_data:
                return User(user_data)
            return None
        except Exception as e:
            print(f"Error loading user: {str(e)}")
            return None

    def register(self, username, password, email=None, phone=None, nickname=None):
        try:
            # 检查用户名是否已存在
            existing_user = self.db_util.get_one(
                'SELECT id FROM user WHERE username = %s AND is_deleted = 0',
                (username,)
            )
            if existing_user:
                return False, '用户名已存在'
            
            # 创建新用户
            hashed_password = generate_password_hash(password)
            sql = '''
                INSERT INTO user (username, password, email, phone, nickname, status, created_time)
                VALUES (%s, %s, %s, %s, %s, 1, %s)
            '''
            self.db_util.execute_update(
                sql,
                (username, hashed_password, email, phone, nickname, datetime.now())
            )
            return True, '注册成功'
        except Exception as e:
            return False, str(e)
    
    def login(self, username, password):
        try:
            # 查询用户信息
            sql = '''
                SELECT id, username, nickname, email, phone, avatar, status, 
                       password, is_deleted, created_time, update_time, last_login_time
                FROM user
                WHERE username = %s AND is_deleted = 0
            '''
            user_data = self.db_util.get_one(sql, (username,))
            
            if not user_data:
                return None, '用户不存在'
            
            if user_data['status'] != 1:
                return None, '账号已被禁用'
            
            if not check_password_hash(user_data['password'], password):
                return None, '密码错误'
            
            # 更新最后登录时间
            self.db_util.execute_update(
                'UPDATE user SET last_login_time = %s WHERE id = %s',
                (datetime.now(), user_data['id'])
            )
            
            # 返回User对象
            return User(user_data), '登录成功'
        except Exception as e:
            return None, str(e)

    def update_user_profile(self, user_id, email=None, phone=None, nickname=None, avatar=None):
        try:
            # 构建更新字段
            update_fields = []
            params = []
            if email is not None:
                update_fields.append('email = %s')
                params.append(email)
            if phone is not None:
                update_fields.append('phone = %s')
                params.append(phone)
            if nickname is not None:
                update_fields.append('nickname = %s')
                params.append(nickname)
            if avatar is not None:
                update_fields.append('avatar = %s')
                params.append(avatar)
            
            if not update_fields:
                return False, '没有需要更新的信息'
            
            # 构建并执行SQL语句
            sql = f"UPDATE user SET {', '.join(update_fields)}, update_time = %s WHERE id = %s AND is_deleted = 0"
            params.extend([datetime.now(), user_id])
            
            affected_rows = self.db_util.execute_update(sql, tuple(params))
            if affected_rows > 0:
                return True, '用户信息更新成功'
            return False, '用户不存在或信息未变更'
        except Exception as e:
            return False, str(e)
    
    def update_user_password(self, user_id, old_password, new_password):
        try:
            # 验证旧密码
            user = self.db_util.get_one(
                'SELECT password FROM user WHERE id = %s AND is_deleted = 0',
                (user_id,)
            )
            
            if not user:
                return False, '用户不存在'
            
            if not check_password_hash(user['password'], old_password):
                return False, '原密码错误'
            
            # 生成新密码哈希并更新
            new_password_hash = generate_password_hash(new_password)
            affected_rows = self.db_util.execute_update(
                'UPDATE user SET password = %s, update_time = %s WHERE id = %s AND is_deleted = 0',
                (new_password_hash, datetime.now(), user_id)
            )
            
            if affected_rows > 0:
                return True, '密码更新成功'
            return False, '密码更新失败'
        except Exception as e:
            return False, str(e)